﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS对账明细生成信息
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMSShippingorder_BillCreateInfo : ControllerBase
    {
        private readonly ILogger<TMSShippingorder_BillCreateInfoRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public TMSShippingorder_BillCreateInfo(ILogger<TMSShippingorder_BillCreateInfoRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");

        }

        /// <summary>
        /// TMS对账明细生成信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSShippingorder_BillCreateInfo([FromBody] TMSShippingorder_BillCreateInfoRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSShippingorder_BillCreateInfoResponseDto re = new TMSShippingorder_BillCreateInfoResponseDto();
            string shippingorderno = strparm.shippingorderno;

            //框架查询方法
            //var data = _WMSTokenCheckService.GetTokenCheckData(supplier_code);
            decimal yprice = 0;
            string address1 = "";
            string address2 = "";
            string typecode = "";
            string cartypename = "";
            decimal materialamount = 0;
            decimal cprice = 0;
            decimal car_pooling = 0;
            string factory_code = "";
            string statementno = "DZ" + DateTime.Now.ToString("yyMMddHHmmss");
            string carno = "";
            string carriercode = "";
            string carriername = "";
            string ddate = "";





            try
            {

                strSql = new StringBuilder();
                strSql.Append(@"select shippingorderno,startaddress,targetaddress,cartypecode from shippingorder_plan_details where  shippingorderno='"+ shippingorderno + "' group by startaddress,targetaddress,shippingorderno,cartypecode ");
                DataTable dt_ydrow = DB.Query(strSql.ToString(), con);

                foreach (DataRow item in dt_ydrow.Rows)
                {
                    string startaddress = item["startaddress"].ToString();
                    string targetaddress = item["targetaddress"].ToString();
                    string cartypecode = item["cartypecode"].ToString();

                    decimal price = 0;


                    strSql = new StringBuilder();
                    strSql.Append(@"select * from tms_base_freight where start_address='"+ startaddress + "' and 	target_address='"+ targetaddress + "' and " +
                        "	cartypecode='" + cartypecode + "' order by creation_date  desc  LIMIT 1");
                    DataTable dt_price = DB.Query(strSql.ToString(), con);
                    if (dt_price.Rows.Count > 0)
                    {
                        price = DB.ToDecimal(dt_price.Rows[0]["freightprice"].ToString());

                        if (yprice==0)
                        {
                            yprice = price;
                            address1 = dt_price.Rows[0]["start_address"].ToString();
                            address2 = dt_price.Rows[0]["target_address"].ToString();
                            typecode = dt_price.Rows[0]["cartypecode"].ToString();

                        }
                        else
                        {
                            if (yprice>= price)
                            {
                                yprice = price;
                                address1 = dt_price.Rows[0]["start_address"].ToString();
                                address2 = dt_price.Rows[0]["target_address"].ToString();
                                typecode = dt_price.Rows[0]["cartypecode"].ToString();
                            }
                        }
                    }

                }

                if (yprice==0)
                {
                    strMsg = "价格获取失败，检查运价档案是否已经录入相关数据";
                }
                else
                {
                    strSql = new StringBuilder();
                    strSql.Append(@"select ma.factory_name,shd.shippingorderno,ma.carriercode,ma.carriername,ma.carno2,ma.ddate,shd.cartypecode,shd.cartypename,sum(shd.materialamount) materialamount,sum(shd.cprice) cprice,sum(shd.car_pooling) car_pooling 
from shippingorder_plan_details shd left join shippingorder_main ma  on shd.shippingorderno=ma.ccode  where  shd.shippingorderno='" + shippingorderno + "'  group by  ma.factory_name,shd.shippingorderno,shd.cartypecode,shd.cartypename,ma.carriercode,ma.carriername,ma.carno2,ma.ddate LIMIT 1");
                    DataTable dt_ydprice = DB.Query(strSql.ToString(), con);
                    if (dt_ydprice.Rows.Count>0)
                    {

                        cartypename = dt_ydprice.Rows[0]["cartypename"].ToString();
                        materialamount = DB.ToDecimal(dt_ydprice.Rows[0]["materialamount"].ToString());
                        cprice = DB.ToDecimal(dt_ydprice.Rows[0]["cprice"].ToString());
                        car_pooling = DB.ToDecimal(dt_ydprice.Rows[0]["car_pooling"].ToString());

                        factory_code= dt_ydprice.Rows[0]["factory_name"].ToString();
                        carriercode = dt_ydprice.Rows[0]["carriercode"].ToString();
                        carriername = dt_ydprice.Rows[0]["carriername"].ToString();
                        carno = dt_ydprice.Rows[0]["carno2"].ToString();
                        ddate= dt_ydprice.Rows[0]["ddate"].ToString();

                    }
                    else
                    {
                        strMsg = "找不到对应运单记录";
                    }

                }

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                dic.Add("factory_code", factory_code);
                dic.Add("statementno", statementno);
                dic.Add("shippingorder_no", shippingorderno);
                dic.Add("carriercode", carriercode);
                dic.Add("carriername", carriername);
                dic.Add("carno", carno);
                dic.Add("cartypecode", typecode);
                dic.Add("startaddress", address1);
                dic.Add("endaddress", address2);
                dic.Add("material_amount", materialamount.ToString());
                dic.Add("cprice", cprice.ToString());
                dic.Add("finalprice", (cprice+ car_pooling).ToString());
                dic.Add("car_pooling", car_pooling.ToString());
                dic.Add("cartypename", cartypename);
                dic.Add("ddate", ddate);
                strMsg = MethodHelp.InsertIntoTable("TMS0007", dic,con);
            }

            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
